package Simple5;

import java.util.HashMap;


/**
 * Find the String expression of digit number,
 * e.g.  1/4 = 0.25
 * 	     1/3 = 0.[3]
 * @author ychi
 *
 */
public class CirculatingDecimal {
	
	public static String digit(int divend, int div){
		StringBuilder sb = new StringBuilder();
		sb.append(divend/div+"");
		if(divend % div == 0)
			return sb.toString();
		else {
			sb.append(".");
		}
		// Handle minus number
		if(divend*div<0){
			divend = ((divend>>31)^divend) - (divend>>31);
			div = ((div>>31) ^ div) - (div>>31);
//			divend = Math.abs(divend);
//			div = Math.abs(div);
			sb.insert(0, "-");
		}
		
		// A HashMap to store the position of each uncirculated digit
		HashMap<Integer, Integer> map = new HashMap<Integer, Integer>();
		int remain = divend % div;
		int startPoint = sb.toString().length();
		map.put(remain, startPoint);
		
		while(remain!=0){
			int cur = remain*10/div;
			sb.append(""+cur);
			remain = remain*10 % div;
			if(map.containsKey(remain)){
				sb.insert(map.get(remain), "[");
				sb.append("]");
				return sb.toString();
			}
			else{
				map.put(remain, ++startPoint);
			}
		}
		
		return sb.toString();
	}
	
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		System.out.println(digit(1, -7));
	}

}
